#include "myheader.h"
ssize_t readn(int fd, void *buf, size_t n) {
    size_t left = n;
    char *ptr =(char *) buf;
    while (left > 0) {
        ssize_t rd = read(fd, ptr, left);
        if (rd < 0) return -1;
        else if (rd == 0) break; // EOF
        left -= rd;
        ptr += rd;
    }
    return n - left;
}
int main(int argc, char *argv[]) {
    int pipefd[2];
    pipe(pipefd);
    
    if (fork() == 0) { // 子进程
        close(pipefd[0]);
        const char *data1 = "hello";
        const char *data2 = "text_context";
        
        // 发送第一段数据
        char len_str[3];
        snprintf(len_str, sizeof(len_str), "%02d", (int)strlen(data1));
        write(pipefd[1], len_str, 2);
        write(pipefd[1], data1, strlen(data1));
        
        // 发送第二段数据
        snprintf(len_str, sizeof(len_str), "%02d", (int)strlen(data2));
        write(pipefd[1], len_str, 2);
        write(pipefd[1], data2, strlen(data2));
        
        close(pipefd[1]);
    } else { // 父进程
        close(pipefd[1]);
        char buf[1024];
        
        // 读取第一段数据
        readn(pipefd[0], buf, 2);
        int len = atoi(buf);
        memset(buf, 0, sizeof(buf));
        readn(pipefd[0], buf, len);
        printf("Data1: %s\n", buf);
        
        // 读取第二段数据
        readn(pipefd[0], buf, 2);
        len = atoi(buf);
        memset(buf, 0, sizeof(buf));
        readn(pipefd[0], buf, len);
        printf("Data2: %s\n", buf);
        
        close(pipefd[0]);
        wait(NULL);
    }
    return 0;
}
